import React, { useEffect, useRef } from "react";
import { ErrorBlock, InfiniteScroll, SearchBar } from "antd-mobile";
import { AssetCard } from "@/components";
import { range } from "lodash-es";
import { getHomelistingsList } from "@/services";
import type { GetHomelistingsListReq, HomelistingsInfo } from "@/services";
import { useGetState, useSafeState } from "ahooks";
const Assets: React.FC = () => {
  const [assetsList, setAssetsList, getAssetsList] = useGetState<
    HomelistingsInfo[]
  >([]);
  const [hasMore, setHasMore] = useSafeState(true);
  const searchName = useRef("");

  type PaginationRef = {
    page: number;
    size: number;
  };
  const paginationRef = useRef<PaginationRef>({
    page: 0,
    size: 10,
  });
  const getAssetsListRequest = async () => {
    const req: GetHomelistingsListReq = {
      name: searchName.current,
      areaCode: "",
      minArea: -1,
      maxArea: -1,
      minStartingBidPrice: -1,
      maxStartingBidPrice: -1,
      auctionStatus: -1,
      auctionMethod: -1,
      type: -1,
      lng: -1,
      lat: -1,
      startCreateTime: "", // 创建时间，开始，如果是今日，则传 yyyy-MM-dd 00:00:00
      endCreateTime: "", // 创建时间，结束，如果是金日，则传 yyyy-MM-dd 23:59:59
      communityName: "", // 小区名称
      stopTime: "", // 停拍时间
      status: -1, // 0-未上架；1-已上架
      sort: -1,
      page: paginationRef.current.page,
      size: paginationRef.current.size,
    };
    const res = await getHomelistingsList(req);
    if (res.code === 200) {
      const newList = [...getAssetsList(), ...res.data.list];

      const total = res.data.total;
      if (total == 0) {
        setHasMore(false);
        setAssetsList([]);
      } else {
        setHasMore(newList.length < total);
        setAssetsList([...getAssetsList(), ...res.data.list]);
      }
    }
  };

  const loadMore = async (isRetry: boolean) => {
    if (!isRetry) {
      paginationRef.current.page = paginationRef.current.page + 1;
    }
    await getAssetsListRequest();
  };

  return (
    <div>
      <div className="w-full bg-white sticky top-0 z-10 py-3 center">
        <SearchBar
          className="w-95%"
          placeholder="请输入内容"
          onSearch={async (val) => {
            searchName.current = val;
            paginationRef.current.page = 1;
            setHasMore(false);
            setAssetsList([]);
            await getAssetsListRequest();
          }}
        />
      </div>
      <div className="w-full h-10rpx"></div>
      {assetsList.map((item) => (
        <AssetCard key={item.onlyId} record={item} />
      ))}
      {assetsList.length === 0 && (
        <div className="mt-100px ">
          <ErrorBlock status="empty" title="暂无数据" description="" />
        </div>
      )}
      <div className="h-70px"></div>
      <InfiniteScroll loadMore={loadMore} hasMore={hasMore} />
    </div>
  );
};

export default Assets;
